package com.app.controller;

import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.PlantVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/plant")
public class PlantController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private PlantService plantService;
    @Autowired
    private DepartmentService departmentService;

    public static final SimpleDateFormat DATA_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @GetMapping("/getPlantList")//场地管理分页查询
    public Result<Object> getPlantList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam("model") String model,
            String departmentName,
            Integer sortType,
            HttpServletRequest request) throws ParseException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        if (user.getDepartmentId()==1){
            idList = new ArrayList<>();
        }
        Page<PlantModel> plantModelPage = plantService.getPagePlantList(page, limit, idList, model,departmentName,sortType);
        if (plantModelPage == null) {
            return Result.error(200, "暂无数据");
        }

        for (int i = 0; i < plantModelPage.getRecords().size(); i++) {//查其他表
//            if (plantModelPage.getRecords().get(i).getWarehousingDate() != null && !plantModelPage.getRecords().get(i).getWarehousingDate().equals("")) {
//                DATA_FORMAT.parse(plantModelPage.getRecords().get(i).getWarehousingDate());
//            }
//            if (plantModelPage.getRecords().get(i).getDeliveryDate() != null && !plantModelPage.getRecords().get(i).getDeliveryDate().equals("")) {
//                DATA_FORMAT.parse(plantModelPage.getRecords().get(i).getDeliveryDate());
//            }
//            if (plantModelPage.getRecords().get(i).getDepartmentId() != null) {
//                DepartmentModel departmentModel = departmentService.getDepByDepId(plantModelPage.getRecords().get(i).getDepartmentId());
//                if (departmentModel != null) {
//                    plantModelPage.getRecords().get(i).setDepartmentName(departmentModel.getName());//获取部门名字
//                }
//            }
            if (plantModelPage.getRecords().get(i).getIsXx() != null && plantModelPage.getRecords().get(i).getIsXx() == 1) {
                plantModelPage.getRecords().get(i).setIsXxText("有");
            } else if (plantModelPage.getRecords().get(i).getIsXx() != null) {
                plantModelPage.getRecords().get(i).setIsXxText("无");
            }
            if (plantModelPage.getRecords().get(i).getIsEngine() != null && plantModelPage.getRecords().get(i).getIsEngine() == 1) {
                plantModelPage.getRecords().get(i).setIsEngineText("有");
            } else if (plantModelPage.getRecords().get(i).getIsEngine() != null) {
                plantModelPage.getRecords().get(i).setIsEngineText("无");
            }
        }
        int count = (int) plantModelPage.getTotal();
        List<PlantModel> plantModelList;
        plantModelList = plantModelPage.getRecords();
        PlantVo vo = new PlantVo();
        vo.setCount(count);
        vo.setList(plantModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertPlant")//    新增/修改场地管理
    public Result<Object> insertPlant(@RequestBody PlantModel model, HttpServletRequest request) {

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        try {
            if (model.getId() > 0) {
                model.setUpdateTime(CommonHelp.getNowTimestamp());
                plantService.update(model);
            } else {
                model.setCreateTime(CommonHelp.getNowTimestamp());
                plantService.insert(model);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success("操作成功");
    }

    @GetMapping("/deleteById")//删除场地
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        PlantModel plantModel = plantService.getPlantById(id);
        if (plantModel == null) {
            return Result.error(500, "该角色不存在");
        } else {
            plantService.delete(id);
            return Result.success(null);
        }
    }

    //批量删除场地信息
    @DeleteMapping("/deletePlantBatchByIds")
    public Result<Object> deleteCarBatchByIds(@RequestParam("ids") String ids, HttpServletRequest request){
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return plantService.deletePlantBatchByIds(ids);
    }
    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
